package com.example.cqcet_demo.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.cqcet_demo.R;
import com.example.cqcet_demo.adapter.MyListViewQueryAdapter;
import com.example.cqcet_demo.bean.Consume;
import com.example.cqcet_demo.uitls.OkHttpUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Mr.z on 2017/6/19.
 */

public class RecordFragment extends Fragment {

    private TextView tv_1;
    private Spinner monthSpinner;
    private Button btn_query;
    private TextView tv_error;
    private View view;
    private LinearLayout rb_layout_query;

    private final String CARDHOLDER_URL = "http://ecard.cqcet.edu.cn/Cardholder/AccBalance.aspx";
    private final String QUERY_URL = "http://ecard.cqcet.edu.cn/Cardholder/Queryhistory.aspx";
    private final String POST_QUERY_URL = "http://ecard.cqcet.edu.cn/Cardholder/QueryhistoryDetailFrame.aspx";
    private String select_month;
    private ListView mListView;
    private List<Consume> consumes;

    private OkHttpClient okHttpClient;
    private Handler mhandler;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (view == null) {
            view = inflater.inflate(R.layout.activity_record, container, false);
            getData();
        }
        return view;
    }



    private void initView() {
        monthSpinner = (Spinner)view.findViewById(R.id.month_spinner);
        tv_1 = (TextView) view.findViewById(R.id.tv_1);
        btn_query = (Button)view.findViewById(R.id.btn_query);
        mListView = (ListView) view.findViewById(R.id.lv_datas);
        tv_error = (TextView) view.findViewById(R.id.tv_error);
        rb_layout_query = (LinearLayout)view.findViewById(R.id.pb_layout_query);
    }

    public void getRecordData() {
        new Thread(){
            @Override
            public void run() {
                okHttpClient = OkHttpUtil.getInstance();
                Request res = new Request.Builder().url(CARDHOLDER_URL).get().build();
                try {
                    Response rsp = okHttpClient.newCall(res).execute();
                    if(rsp.isSuccessful()){
                        Message msg = new Message();
                        String data = rsp.body().string();
                        Log.d("record","record执行成功");
                        Document doc = Jsoup.parse(data, "GBK");

                        String accountNumber = doc.getElementById("lblOne0").text();

                        msg.what = 0x121;
                        msg.obj = accountNumber;

                        mhandler.sendMessage(msg);

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    protected void getData() {
        initView();

        Calendar c = Calendar.getInstance();
        List<String> months = new ArrayList<>();
        int month = c.get(Calendar.MONTH) + 1;
        for (int i = 1; i <= month; i++) {
            months.add(i + "   月");
        }
        monthSpinner.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, months));


        getRecordData();
        btn_query.setOnClickListener(new MyOnClickListener());


        mhandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0x121:
                        tv_1.setText(msg.obj.toString());
                        break;
                    case 0x122:
                        rb_layout_query.setVisibility(View.GONE);
                        tv_error.setVisibility(View.GONE);
                        mListView.setVisibility(View.VISIBLE);
                        mListView.setAdapter(new MyListViewQueryAdapter(getContext(), consumes));
                        break;
                    case 0x123:
                        rb_layout_query.setVisibility(View.GONE);
                        tv_error.setText(select_month + "月暂无消费信息");
                        mListView.setVisibility(View.GONE);
                        tv_error.setVisibility(View.VISIBLE);
                        break;
                }

            }
        };

    }

    class MyOnClickListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn_query:
                    rb_layout_query.setVisibility(View.VISIBLE);
                    select_month = monthSpinner.getSelectedItem().toString().split(" ")[0];
                    getQueryData();
                    break;
            }
        }
    }

    private void getQueryData() {
        consumes = new ArrayList<>();
        new Thread(){
            @Override
            public void run() {

                Request res = new Request.Builder().url(QUERY_URL).get().build();
                try {
                    Response rsp = okHttpClient.newCall(res).execute();
                    if(rsp.isSuccessful()){

                        Document doc = Jsoup.parse(rsp.body().string(), "GBK");
                        String viewstate = doc.select("input[name=\"__VIEWSTATE\"]").first().attr("value");
                        Log.d("__VIEWSTATE","__VIEWSTATE"+viewstate);
                        RequestBody requestBody = new FormBody.Builder()
                                .add("__VIEWSTATE",viewstate)
                                .add("ddlYear", "2017")
                                .add("ddlMonth",select_month)
                                .add("txtMonth",select_month)
                                .add("ImageButton1.x","22")
                                .add("ImageButton1.y","16").build();
                        res = new Request.Builder().url(QUERY_URL).post(requestBody).build();
                        rsp = okHttpClient.newCall(res).execute();
                        if(rsp.code()==302){
                            String data = rsp.body().string();
                            if(data.contains("QueryhistoryDetail")){
                                res = new Request.Builder().url(POST_QUERY_URL).get().build();
                                rsp = okHttpClient.newCall(res).execute();
                                data = rsp.body().string();
                                doc = Jsoup.parse(data, "GBK");
                                Log.d("doc",data);
                                //解析数据
                                Elements trs;
                                try {
                                    trs = doc.getElementById("dgShow").select("tr");
                                }catch (NullPointerException e){
                                    e.printStackTrace();
                                    Message msg = new Message();
                                    msg.what = 0x123;
                                    mhandler.sendEmptyMessage(msg.what);
                                    return;
                                }
                                for (int i = trs.size()-1;i > 0;i--){
                                    Elements tds = trs.get(i).select("td");
                                    Consume cs = new Consume();
                                    //cs.setType(tds.get(3).text());
                                    cs.setAddress(tds.get(4).text());
                                    String priceNum =tds.get(7).text();
                                    try {
                                        priceNum = Integer.parseInt(priceNum)>0 ?"+"+priceNum:priceNum;

                                    }catch (NumberFormatException e){
                                        e.printStackTrace();
                                    }
                                    cs.setPrice(priceNum);
                                    cs.setDate(tds.get(8).text());
                                    cs.setBalance(tds.get(10).text());
                                    consumes.add(cs);
                                }
                                Message msg = new Message();
                                msg.what = 0x122;
                                mhandler.sendEmptyMessage(msg.what);

                            }
                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}
